class Ticket < ActiveRecord::Base
  belongs_to :order
  belongs_to :customer
  belongs_to :customer_backup
  belongs_to :policy
  belongs_to :passenger, :class_name => 'Customer', :foreign_key => 'passenger_id' #常旅客
  belongs_to :canceler, :class_name => 'User', :foreign_key => 'canceler_id' #取消人
  belongs_to :insurance_outer, :class_name => 'User', :foreign_key => 'insurance_outer_id' #出保险人
  
  #取消票和订单记录
  def self.cancelOrderAndTicket(oid,uid,reason)
    begin
      result = false
      transaction do #事务
        order = Order.find_by_id(oid)
        if order
          order.canceler_id = uid.to_i
          order.cancel_date = Time.new
          order.cancel_reason = reason
          order.status = Constants::ORDER_STATUS_YQX
          order.save
          #Ticket.update_all(["status=?",Constants::TICKET_STATUS_YQX], :order_id => oid)
          for ticket in order.tickets
            ticket.canceler_id = uid.to_i
            ticket.cancel_date = Time.new
            ticket.cancel_reason = reason
            ticket.status = Constants::TICKET_STATUS_YQX
            ticket.save
          end
          result = true
        end
      end
      return result
    rescue Exception => e
      logger.error  "Ticket cancelOrderAndTicket :: e="+e.message
    end
  end
  
  #取消票记录
  def self.cancelTicketFromOrder(tid,uid,reason)
    begin
      result = false
      transaction do #事务
        ticket = Ticket.find_by_id(tid)
        if ticket
          total_price = 0
          #取消该乘客在这个订单中的所有记录
          tickets = Ticket.find(:all,:conditions=>["order_id=? and passenger_id=? and is_locked<>1",ticket.order_id,ticket.passenger_id])
          for ticket in tickets
            total_price += ticket.total_price
            
            ticket.canceler_id = uid.to_i
            ticket.cancel_date = Time.new
            ticket.cancel_reason = reason
            ticket.status = Constants::TICKET_STATUS_YQX
            if ticket.save
              result = true
            else
              result = false
              break
            end
          end
          #订单总价格中减去票价 乘客人数减1
          order = ticket.order
          order.seat -= 1
          order.price_sum -= total_price
          order.save
        end
      end
      return result
    rescue Exception => e
      logger.error  "Ticket cancelTicketFromOrder :: e="+e.message
      return false
    end
  end
  
end
